﻿using System;
using System.Reflection;
using System.ServiceModel;
using MouseExtender.LoggingService;
using MouseExtender.Logic.Common;

namespace MouseExtender.Logic.Managers
{
    public class ErrorReportManager
    {
        public static void SubmitReport(Guid errorId, bool isCritical, string errorMessage, string errorDetails)
        {
            Action<Guid, bool, string, string> submitReport = SubmitReprotInternally;
            submitReport.BeginInvoke(errorId, isCritical, errorMessage, errorDetails, null, null);
        }

        private static void SubmitReprotInternally(Guid errorId, bool isCritical, string errorMessage, string errorDetails)
        {
            try
            {
                var report = new ErrorReport()
                {
                    Id = errorId,
                    ApplicationInstanceId = SettingsManager.CurrentSettings.ApplicationInstanceId.Value,
                    ApplicationVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(),
                    IsCritical = isCritical,
                    ErrorMessage = errorMessage,
                    ErrorDetails = errorDetails,
                };

                var binding = new BasicHttpBinding();
                var endPoint = new EndpointAddress(string.Format("{0}/WebServices/LoggingService.svc", Constants.MeSiteUrl));
#if DEBUG
                endPoint = new EndpointAddress("http://localhost:30016/WebServices/LoggingService.svc");
#endif
                LoggingServiceClient loggingProxy = null;
                try
                {
                    loggingProxy = new LoggingServiceClient(binding, endPoint);
                    loggingProxy.SubmitErrorReport(report);
                }
                catch
                {
                    if (loggingProxy != null)
                    {
                        loggingProxy.Abort();
                    }
                    throw;
                }
                finally
                {
                    if (loggingProxy != null)
                    {
                        loggingProxy.Close();
                    }
                }

            }
            catch (Exception ex)
            {
                Logger.HandleNonCriticalError(ex, false);
            }
        }
    }
}
